package com.ybkj.daijia.api.weixin.v2;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.api.weixin.WeixinUtil;
import com.ybkj.daijia.common.IpHelper;
import com.ybkj.daijia.common.RandomString;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.OrderNewRushEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.MemberLogin;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.OrderCarType;
import com.ybkj.daijia.server.model.Order.OrderCarTypeDetail;
import com.ybkj.daijia.server.model.PhoneSmsRecord;
import com.ybkj.daijia.server.model.WeixinManager;
import com.ybkj.daijia.server.model.WeixinManagerPayments;
import com.ybkj.daijia.server.model.WeixinManagerSetting;
import com.ybkj.daijia.server.model.WeixinManagerTixianRecord;
import com.ybkj.daijia.server.model.WeixinManagerXOrder;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberLoginRecordService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.PhoneSmsRecordService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.WeixinManagerPaymentsService;
import com.ybkj.daijia.server.service.WeixinManagerService;
import com.ybkj.daijia.server.service.WeixinManagerSettingService;
import com.ybkj.daijia.server.service.WeixinManagerTixianRecordService;
import com.ybkj.daijia.server.service.WeixinManagerXOrderService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 客户经理相关
 *
 * @author mqs
 */
@Controller("WxConsumerManagerV2")
@RequestMapping(value = "wx/v2/wxManager")
public class WxConsumerManager {

    private static final Logger logger = LoggerFactory.getLogger(WxConsumerManager.class);

    @Autowired
    private WeixinManagerService weixinManagerService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private WeixinManagerXOrderService weixinManagerXOrderService;

    @Autowired
    private WeixinManagerTixianRecordService weixinManagerTixianRecordService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PhoneSmsRecordService phoneSmsRecordService;

    @Autowired
    private ErrandService errandService;

    @Autowired
    private WeixinManagerSettingService weixinManagerSettingService;


    @Autowired
    private WeixinManagerPaymentsService weixinManagerPaymentsService;


    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private SmsService smsService;

    @Autowired
    private MemberLoginRecordService memberLoginRecordService;


    /**
     * 首頁
     *
     * @param model
     * @return
     */
    @RequestMapping("/")
    public String index(Model model) {
        WxSetting wxSetting = settingUtils.getWx();

        model.addAttribute("wxAppId", wxSetting.getWxAppId());

        return "wxmanagerweb/v2/index";
    }


    /**
     * 获取openId和相关登录信息
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "getOpenId", method = RequestMethod.GET)
    public @ResponseBody
    Result<String> getOpenId(HttpServletResponse response, String jsCode, String openId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<String> result = new Result<String>();
        result.setSuccess(false);

        WxSetting setting = settingUtils.getWx();
        String appId = setting.getWxAppId();
        String secret = setting.getWxAppSecret();

        if (StringUtils.isNotBlank(jsCode)) {
            String openId2 = HttpClientUtil.getUserInfo(jsCode, appId, secret);
            if (StringUtils.isNotBlank(openId2)) {
                openId = openId2;
            }
        }

        if (StringUtils.isNotBlank(openId)) {

            result.setResult(openId);

            WeixinManager weixinManager = weixinManagerService.findByWxuser(openId);
            if (null != weixinManager) {
                if (weixinManager.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                    result.setErrorcode("WAITAUDIT");//等待审核
                    return result;
                } else if (weixinManager.getStatus()
                    .equals(WeixinManager.WEIXINMANAGER_STATUS_FAILURE)) {
                    result.setErrorcode("AUDITFAILED");//审核失败
                    result.setMessage(weixinManager.getAuditMemo());
                    result.setObject(weixinManager);
                    return result;
                } else {
//                  if(StringUtils.isBlank(weixinManager.getWxuser())){
//                    result.setErrorcode("BINDNULL");//openId未绑定
//                    return result;
//                  }
//                  else{
                    result.setSuccess(true);
                    result.setObject(weixinManager);
                    return result;//
//                  }
                }
            } else {
                result.setErrorcode("MANAGERNULL");//客户经理不存在
                return result;//跳转登录
            }
        } else {
            result.setErrorcode("OPENIDNULL");//未获取到openId
            return result;
        }
    }

    /**
     * 发送登录验证码
     *
     * @param phone
     * @return
     */
    @RequestMapping("smsQrCode")
    public @ResponseBody
    Result<PhoneSmsRecord> smsQrCode(HttpServletRequest request, HttpServletResponse response,
        String phone, String imagesVerify) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<PhoneSmsRecord> result = new Result<PhoneSmsRecord>();

        ResultTransport compareImageVerifyFun = compareImageVerifyFun(phone, imagesVerify);
        if (compareImageVerifyFun.getCode() != 0) {// 图形验证码验证失败
            result.setMessage(compareImageVerifyFun.getMessage());
            return result;
        }

        Company company = companyService.getMain();

        PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);

        String IP = IpHelper.getIp(request);

        if (null != phoneSmsRecord) {
            long time = (System.currentTimeMillis() - phoneSmsRecord.getExpired().getTime()) / 1000;//多少秒
            if (time < 120) {//2分内禁止发送
                result.setErrorcode("0");
                result.setObject(120 - time);
                return result;
            } else if (time >= 120 && time < 30 * 60) {//30分内发送旧的
                result.setErrorcode("1");
                try {
                    smsService.sendSmsMsg(IP, phone, phoneSmsRecord.getVcode(), company.getId(),
                        company.getAbbreviation(), company.getSignName()); // 发送验证码

                    result.setSuccess(true);
                    phoneSmsRecord.setExpired(new Date());
                    phoneSmsRecordService.update(phoneSmsRecord);
                } catch (Exception e) {

                }
                return result;
            } else {//超过30分 发送新的
                result.setErrorcode("1");
                String newCode = String.valueOf(RandomString.randomNum(4));
                try {
                    smsService
                        .sendSmsMsg(IP, phone, newCode, company.getId(), company.getAbbreviation(),
                            company.getSignName()); // 发送验证码

                    result.setSuccess(true);
                    phoneSmsRecord.setExpired(new Date());
                    phoneSmsRecord.setVcode(newCode);
                    phoneSmsRecordService.update(phoneSmsRecord);
                } catch (Exception e) {
                }
                return result;
            }
        } else {
            result.setErrorcode("1");
            String newCode = String.valueOf(RandomString.randomNum(4));
            try {
                smsService
                    .sendSmsMsg(IP, phone, newCode, company.getId(), company.getAbbreviation(),
                        company.getSignName()); // 发送验证码

                result.setSuccess(true);
                phoneSmsRecord = new PhoneSmsRecord();
                phoneSmsRecord.setCompanyId(company.getId());
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecord.setVcode(newCode);
                phoneSmsRecordService.save(phoneSmsRecord);
            } catch (Exception e) {
            }
            return result;
        }

    }

    private ResultTransport compareImageVerifyFun(String phone, String imagesVerify) {
        if (StringUtils.isBlank(imagesVerify)) {
            return ResultTransport.getErrorBy(ErrorConstant.COMPARE_IMAGE_VERIFY_ERROR);
        }
        // 获取该用户登录信息
        Map<String, Object> findLoginRecordMap = memberLoginRecordService.findLoginRecord(phone);
        if (!(boolean) findLoginRecordMap.get("isExist")) {// 登录信息不存在
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_LOGIN_ERROR);
        }
        MemberLogin memberLogin = (MemberLogin) findLoginRecordMap.get("data");
        if (System.currentTimeMillis() - memberLogin.getIvcTime().getTime()
            < MemberLogin.IVC_VALID_TIME) {
            // 该图形验证码有效
            if (!memberLogin.getImagesVerifyCode().equalsIgnoreCase(imagesVerify)) {// 图形验证码匹配错误
                return ResultTransport.getErrorBy(ErrorConstant.COMPARE_IMAGE_VERIFY_ERROR);
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("result", true);
                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
                instance.setCode(0);
                instance.setData(map);
                return instance;
            }
        } else {// 该图形验证码失效
            return ResultTransport.getErrorBy(ErrorConstant.IMAGE_VERIFY_INVALID);
        }
    }

    /**
     * 验证码登录
     *
     * @param openId
     * @param phone
     * @param code
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public @ResponseBody
    Result<WeixinManager> login(HttpServletResponse response, String openId, String phone,
        String code) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<WeixinManager> result = new Result<WeixinManager>();
        result.setObject("0");
        result.setSuccess(false);

        if (StringUtils.isBlank(openId) || StringUtils.isBlank(phone) || StringUtils
            .isBlank(code)) {
            result.setMessage("参数错误");
            return result;
        }

        PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);
        if (null == phoneSmsRecord || !phoneSmsRecord.getVcode().equals(code)) {
            result.setMessage("验证码错误");
            return result;
        }

        WeixinManager weixinManager = weixinManagerService.findByPhone(phone);

        if (null != weixinManager) {
            if (StringUtils.isBlank(weixinManager.getWxuser()) && weixinManager.getStatus()
                .equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
                weixinManager.setWxuser(openId);
                weixinManagerService.updateByPrimaryKey(weixinManager);
                result.setObject("1");
            }
        }

        phoneSmsRecordService.deleteByPhone(phone);

        result.setSuccess(true);
        return result;

    }

    /**
     * 验证码绑定
     *
     * @param openId
     * @param phone
     * @param code
     * @return
     */
    @RequestMapping(value = "bind", method = RequestMethod.POST)
    public @ResponseBody
    Result<WeixinManager> bind(HttpServletResponse response, String openId, String phone,
        String code) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<WeixinManager> result = new Result<WeixinManager>();
        result.setSuccess(false);

        if (StringUtils.isBlank(openId) || StringUtils.isBlank(phone) || StringUtils
            .isBlank(code)) {
            result.setMessage("参数错误");
            return result;
        }

        PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);
        if (null == phoneSmsRecord || !phoneSmsRecord.getVcode().equals(code)) {
            result.setMessage("验证码错误");
            return result;
        }

        WeixinManager weixinManager = weixinManagerService.findByPhone(phone);
        weixinManager.setWxuser(openId);
        weixinManagerService.updateByPrimaryKey(weixinManager);

        phoneSmsRecordService.deleteByPhone(phone);

        result.setSuccess(true);
        return result;

    }


    /**
     * 合作协议
     *
     * @param model
     * @return
     */
    @RequestMapping("agreement")
    public String agreement(Model model) {
        WeixinManagerSetting weixinManagerSetting = weixinManagerSettingService.findOne();

        String agreement = "";
        if (null != weixinManagerSetting) {
            agreement = weixinManagerSetting.getAgreement();
        }

        model.addAttribute("agreement", agreement);
        return "wxmanagerweb/v2/agreement";
    }

    /**
     * 获取公司信息
     *
     * @param longitude
     * @param latitude
     * @return
     */
    @RequestMapping(value = "getCompanys", method = RequestMethod.GET)
    public @ResponseBody
    Result<Company> getCompanys(HttpServletResponse response, Double longitude, Double latitude) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<Company> result = new Result<Company>();
        result.setSuccess(false);

        List<Company> companys = companyService.findAll();

        String cityName = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
        Long companyId = null;
        if (StringUtils.isNotBlank(cityName)) {
            for (Company company : companys) {
                if (company.getCityName().equals(cityName)) {
                    companyId = company.getId();
                    break;
                }
            }
        }

        result.setData(companys);
        result.setLongValue(companyId);
        return result;
    }

    /**
     * 客户经绑定申请
     *
     * @param weixinManager
     * @param openId
     * @return
     */
    @RequestMapping(value = "managerApply", method = RequestMethod.POST)
    public @ResponseBody
    Result<WeixinManager> managerApply(HttpServletResponse response, WeixinManager weixinManager,
        String openId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug(
            "recv place:{},lat:{},lng:{},openId:{},name:{},phone:{},idCard:{},jobNumber:{},personalInfo{}",
            weixinManager.getPlace(), weixinManager.getLatitude(), weixinManager.getLongitude(),
            openId,
            weixinManager.getName(), weixinManager.getPhone(), weixinManager.getIdCard(),
            weixinManager.getJobNumber(), weixinManager.getPersonalInfo());

        Result<WeixinManager> vo = new Result<WeixinManager>();
        vo.setSuccess(false);

        if (StringUtils.isBlank(weixinManager.getPlace()) || null == weixinManager.getLatitude()
            || null == weixinManager.getLongitude() || StringUtils.isBlank(openId)
            || StringUtils.isBlank(weixinManager.getName()) || StringUtils
            .isBlank(weixinManager.getPhone())) {
            vo.setMessage("参数错误");
            return vo;
        }

        WeixinManager db_weixinManager = weixinManagerService.findByWxuser(openId);

        if (null != db_weixinManager) {
            if (db_weixinManager.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_NOTYET)) {
                vo.setMessage("申请正在审核中，不能重复申请");
                return vo;
            }
            if (db_weixinManager.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
                vo.setMessage("已审核通过，不能重复申请");
                return vo;
            }
        }

        Long managerId = null;
        if (null != db_weixinManager) {
            managerId = db_weixinManager.getId();
        }

        if (phoneExists(weixinManager.getPhone(), managerId)) {
            vo.setMessage("手机号" + weixinManager.getPhone() + "已申请过客户经理");
            return vo;
        }
        if (idCardExists(weixinManager.getIdCard(), managerId)) {
            vo.setMessage("身份证号" + weixinManager.getIdCard() + "已申请过客户经理");
            return vo;
        }

        Map<String, String> map = HttpClientUtil
            .getProvinceCityByLngAndLat(weixinManager.getLongitude(), weixinManager.getLatitude());
        if (null == map) {
            vo.setMessage("获取地理信息失败，请稍后再试");
            return vo;
        }

        weixinManager.setProvName(map.get("province"));
        weixinManager.setCityName(map.get("city"));

        if (null == managerId) {
            weixinManager.setWxuser(openId);
            weixinManager.setVirtual(BigDecimal.ZERO);
            weixinManager.setStatus(WeixinManager.WEIXINMANAGER_STATUS_NOTYET);
            weixinManagerService.insertRecord(weixinManager);
        } else {
            weixinManager.setId(managerId);
            weixinManager.setWxuser(openId);
            weixinManager.setVirtual(BigDecimal.ZERO);
            weixinManager.setStatus(WeixinManager.WEIXINMANAGER_STATUS_NOTYET);
            weixinManagerService.updateByPrimaryKey(weixinManager);
        }

        vo.setSuccess(true);
        return vo;
    }

    /**
     * 获取订单列表数据
     *
     * @param openId
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "orderRecordsData", method = RequestMethod.GET)
    public @ResponseBody
    Result<Page<Map<String, Object>>> orderRecordsData(
        HttpServletResponse response, String openId, Integer page, Integer limit) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<Page<Map<String, Object>>> result = new Result<Page<Map<String, Object>>>();
        if (StringUtils.isNotBlank(openId)) {

            WeixinManager wm = weixinManagerService.findByWxuser(openId);

            Page<Map<String, Object>> p = weixinManagerXOrderService
                .queryByManagerId(wm.getId(), page, limit);

            result.setSuccess(true);
            result.setResult(p);
            return result;

        }
        return result;

    }

    /**
     * 客户经理销单
     *
     * @param openId
     * @param orderId
     * @param memo
     * @return
     */
    @RequestMapping(value = "cancelOrder", method = RequestMethod.POST)
    public @ResponseBody
    Result<Order> cancelOrder(HttpServletResponse response, String openId, Long orderId,
        String memo) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv openId:{},orderId:{},memo:{}", openId, orderId, memo);

        Result<Order> vo = new Result<Order>();
        vo.setSuccess(false);

        if (StringUtils.isBlank(openId) || null == orderId) {
            vo.setMessage("参数错误");
            return vo;
        }

        WeixinManager db_weixinManager = weixinManagerService.findByWxuser(openId);

        WeixinManagerXOrder wxo = weixinManagerXOrderService.findByOrderId(orderId);
        if (!wxo.getManagerId().equals(db_weixinManager.getId())) {
            vo.setMessage("不属于当前订单");
            return vo;
        }

        Order order = orderService.findOne(orderId);
        if (!order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
            vo.setMessage("只能销单新订单，请联系司机");
            return vo;
        }

        orderService.managerCancel(order, memo);

        vo.setSuccess(true);
        return vo;
    }

    /**
     * 预算价格
     *
     * @param openId
     * @param serverTime
     * @param startLat
     * @param startLng
     * @param endLat
     * @param endLng
     * @return
     */
    @RequestMapping(value = "getPrice", method = RequestMethod.GET)
    public @ResponseBody
    Result<Map<String, Object>> getPrice(
        HttpServletResponse response,
        @RequestParam(required = true, value = "openId") String openId,
        @RequestParam(required = true, value = "serverTime") Long serverTime,
        @RequestParam(required = true, value = "startLat") Double startLat,
        @RequestParam(required = true, value = "startLng") Double startLng,
        @RequestParam(required = false, value = "endLat") Double endLat,
        @RequestParam(required = false, value = "endLng") Double endLng) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        result.setSuccess(false);

        WeixinManager db_weixinManager = weixinManagerService.findByWxuser(openId);

        Double mileage = 0.0;
        Integer time = 0;
        if (endLat != null && endLng != null) {
            Result<Map<String, Long>> restMap = HttpClientUtil
                .getDistanceAndTimeValueByTwoPoints(startLng, startLat, endLng, endLat);
            Long distance = restMap.getResult().get("distance");//米
            Long timemis = restMap.getResult().get("time");//秒
            mileage = new BigDecimal(distance)
                .divide(new BigDecimal(1000), 1, BigDecimal.ROUND_HALF_DOWN).doubleValue();
            time = new BigDecimal(timemis).divide(new BigDecimal(60), 0, BigDecimal.ROUND_HALF_DOWN)
                .intValue();
        }
        Map<String, Object> map = errandService
            .getNewPrice(db_weixinManager.getAreaId(), mileage, time, new Date(serverTime), 0D);

        if ((Boolean) map.get("success")) {
            result.setSuccess(true);
            result.setResult(map);
            return result;
        } else {
            result.setMessage((String) map.get("message"));
            return result;
        }
    }


    /**
     * 个人中心数据
     *
     * @param openId
     * @return
     */
    @RequestMapping(value = "profile", method = RequestMethod.GET)
    public @ResponseBody
    Result<WeixinManager> profile(HttpServletResponse response, String openId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<WeixinManager> result = new Result<WeixinManager>();

        if (StringUtils.isNotBlank(openId)) {

            WeixinManager wm = weixinManagerService.findByWxuser(openId);

            if (null != wm) {
                Calendar c = Calendar.getInstance();
                c.set(Calendar.DAY_OF_MONTH, 1);
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);

                Date start = c.getTime();
                Date end = new Date();

                BigDecimal totalIncome = weixinManagerXOrderService
                    .sumMoney(wm.getId(), null, null);
                BigDecimal monthIncome = weixinManagerXOrderService
                    .sumMoney(wm.getId(), start, end);

                wm.setTotalIncome(totalIncome);
                wm.setMonthIncome(monthIncome);

                result.setSuccess(true);
                result.setResult(wm);
                return result;
            } else {
                result.setMessage("该openId客户经理不存在");
            }
        } else {
            result.setMessage("openId为NULL");
        }

        return result;

    }

    @RequestMapping(value = "wxUserInfo", method = RequestMethod.GET)
    public @ResponseBody
    Result<Map<String, Object>> wxUserInfo(HttpServletResponse response, String openId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<Map<String, Object>> result = new Result<Map<String, Object>>();

        if (StringUtils.isNotBlank(openId)) {

            WxSetting wxSetting = settingUtils.getWx();

            Map<String, Object> map = WeixinUtil
                .getWxUserInfo(wxSetting.getWxAppId(), wxSetting.getWxAppSecret(), openId);

            result.setSuccess(true);
            result.setResult(map);
            return result;

        }

        return result;

    }


    /**
     * 变更个人信息
     *
     * @param openId
     * @param place
     * @param placeName
     * @param longitude
     * @param latitude
     * @return
     */
    @RequestMapping(value = "changeMyInfo", method = RequestMethod.POST)
    public @ResponseBody
    Result<Order> changeMyInfo(HttpServletResponse response, String openId, String place,
        String placeName, Double longitude, Double latitude) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv openId:{},place:{},placeName:{},longitude:{},latitude:{}", openId, place,
            placeName, longitude, latitude);

        Result<Order> vo = new Result<Order>();
        vo.setSuccess(false);

        if (StringUtils.isBlank(openId)) {
            vo.setMessage("参数错误");
            return vo;
        }

        Map<String, String> map = HttpClientUtil.getProvinceCityByLngAndLat(longitude, latitude);
        if (null == map) {
            vo.setMessage("获取地理信息失败，请稍后再试");
            return vo;
        }

        WeixinManager db_weixinManager = weixinManagerService.findByWxuser(openId);

        db_weixinManager.setPlace(place);
        db_weixinManager.setPlaceName(placeName);
        db_weixinManager.setLatitude(latitude);
        db_weixinManager.setLongitude(longitude);
        db_weixinManager.setProvName(map.get("province"));
        db_weixinManager.setCityName(map.get("city"));

        weixinManagerService.updateByPrimaryKey(db_weixinManager);

        vo.setSuccess(true);
        return vo;
    }

    /**
     * 查询账户明细
     *
     * @param openId
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "paymentsData", method = RequestMethod.GET)
    public @ResponseBody
    Result<Page<WeixinManagerPayments>> paymentsData(
        HttpServletResponse response, String openId, Integer page, Integer limit) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<Page<WeixinManagerPayments>> result = new Result<Page<WeixinManagerPayments>>();
        if (StringUtils.isNotBlank(openId)) {

            WeixinManager wm = weixinManagerService.findByWxuser(openId);

            Page<WeixinManagerPayments> p = weixinManagerPaymentsService
                .queryByManagerId(wm.getId(), page, limit);

            result.setObject(wm.getVirtual());
            result.setSuccess(true);
            result.setResult(p);
            return result;

        }

        return result;

    }


    /**
     * 申请提现
     *
     * @param weixinManagerTixianRecord
     * @param openId
     * @return
     */
    @RequestMapping("tixianApply")
    public synchronized @ResponseBody
    Result<WeixinManagerTixianRecord> tixianApply(HttpServletResponse response,
        WeixinManagerTixianRecord weixinManagerTixianRecord, String openId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        Result<WeixinManagerTixianRecord> result = new Result<>();

        if (StringUtils.isBlank(openId)) {
            result.setMessage("微信账号为空");
            return result;
        }

        WeixinManager wm = weixinManagerService.findByWxuser(openId);

        if (weixinManagerTixianRecord.getMoney().compareTo(BigDecimal.ZERO) != 1) {
            result.setMessage("无效的金额");
            return result;
        }

        if (wm.getVirtual().subtract(weixinManagerTixianRecord.getMoney())
            .compareTo(BigDecimal.ZERO) == -1) {
            result.setMessage("超出可提现余额");
            return result;
        }

        weixinManagerTixianRecordService.tixianApply(weixinManagerTixianRecord, wm);
        result.setSuccess(true);
        return result;

    }

    /**
     * 客户经理下单
     *
     * @param openId
     * @param longitude
     * @param latitude
     * @param place
     * @param serverTime
     * @param bookType        0联系客户 1联系客户经理
     * @param driverNum
     * @param passengerPhones
     * @return
     */
    @RequestMapping(value = "orderBook", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<Order> orderBook(HttpServletResponse response, String openId, Double longitude,
        Double latitude, String place,
        Long serverTime, Integer bookType, Integer driverNum, String passengerPhones) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug(
            "recv openId:{},longitude:{},latitude:{},place:{},serverTime:{},bookType:{},driverNum:{},passengerPhones:{}",
            openId, longitude, latitude, place, serverTime, bookType, driverNum, passengerPhones);

        Result<Order> vo = new Result<Order>();
        vo.setSuccess(false);

        if (StringUtils.isBlank(openId) || null == longitude || null == latitude || StringUtils
            .isBlank(place)
            || null == serverTime || null == bookType || null == driverNum) {
            vo.setMessage("参数错误");
            return vo;
        }

        if (bookType.equals(0) && StringUtils.isBlank(passengerPhones)) {
            vo.setMessage(" 请输入车主电话");
            return vo;
        }

        if (driverNum <= 0) {
            vo.setMessage("所需司机数量最少为1人");
            return vo;
        }

        if (driverNum > 5) {
            vo.setMessage("所需司机数量最多为5人");
            return vo;
        }

        WeixinManager weixinManager = weixinManagerService.findByWxuser(openId);

        if (!weixinManager.getStatus().equals(WeixinManager.WEIXINMANAGER_STATUS_OK)) {
            vo.setMessage("还未审核通过，不能下单");
            return vo;
        }

        try {
            Order order = new Order();
            order.setClientLongitude(longitude);
            order.setClientLatitude(latitude);
            order.setFromPlace(place);
            order.setServerTime(new Date(serverTime));
            order.setOrderCarType(OrderCarType.daijia);
            order.setOrderCarTypeDetail(OrderCarTypeDetail.jhdj);

            List<String> phones = new ArrayList<String>();
            //新客户电话集合
            List<String> newPassengerPhones = new ArrayList<String>();
            if (bookType.equals(0)) {
                String[] passengerPhoneArr = passengerPhones.split(",");
                for (int i = 0; i < driverNum; i++) {
                    phones.add(passengerPhoneArr[i]);
                    Passenger passenger = memberService
                        .findOnePassengerByPhone(passengerPhoneArr[i]);
                    if (null == passenger) {
                        newPassengerPhones.add(passengerPhoneArr[i]);
                    }
                }
            } else {
                for (int i = 0; i < driverNum; i++) {
                    phones.add(weixinManager.getPhone());
                }
                Passenger passenger = memberService
                    .findOnePassengerByPhone(weixinManager.getPhone());
                if (null == passenger) {
                    newPassengerPhones.add(weixinManager.getPhone());
                }
            }

            List<Order> orderlist = orderService.managerBookV2(weixinManager, order, phones);

            OrderNewRushEvent newRushEvent = new OrderNewRushEvent(orderlist);
            applicationEventMulticaster.multicastEvent(newRushEvent);

            //新客户参加活动
            if (!CollectionUtils.isEmpty(newPassengerPhones)) {
                for (String newPhone : newPassengerPhones) {
                    Passenger passenger = memberService.findOnePassengerByPhone(newPhone);
                    ReactorVo rVo = new ReactorVo();
                    rVo.setPassenger(passenger);
                    rVo.setActivityEvent(ActivityEvent.newRegister);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);
                }
            }
            vo.setSuccess(true);
            return vo;
        } catch (Exception e) {
            vo.setMessage(e.getMessage());
            return vo;
        }
    }

    private boolean idCardExists(String idCard, Long id) {
        WeixinManager wm = weixinManagerService.findByIdCard(idCard);

        if (null != wm) {

            if (null != id && id.equals(wm.getId())) {

                return false;

            }

            return true;
        }

        return false;
    }

    private boolean phoneExists(String phone, Long id) {
        WeixinManager wm = weixinManagerService.findByPhone(phone);

        if (null != wm) {

            if (null != id && id.equals(wm.getId())) {

                return false;

            }

            return true;
        }

        return false;
    }

}

